<template>
  <div class="ticket-list">
    <el-card>
      <template #header>
        <div class="header">
          <h3>📋 工单列表</h3>
          <el-button type="primary" @click="router.push('ticket/create/')">➕ 新建工单</el-button>
        </div>
      </template>
      
      <div class="search-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input v-model="searchForm.keyword" placeholder="搜索项目名称" clearable />
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="状态" clearable>
              <el-option label="待分配" value="pending" />
              <el-option label="进行中" value="progress" />
              <el-option label="已完成" value="completed" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.priority" placeholder="优先级" clearable>
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
              <el-option label="紧急" value="urgent" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <el-table :data="filteredTickets" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="projectName" label="项目名称" min-width="150" />
        <el-table-column prop="projectType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag size="small">{{ getProjectTypeText(row.projectType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="150">
          <template #default="{ row }">
            <el-select
              v-model="row.status"
              size="small"
              @change="handleStatusChange(row)"
              style="width: 120px"
            >
              <el-option label="待分配" value="pending">
                <span style="color: #909399">⏳ 待分配</span>
              </el-option>
              <el-option label="进行中" value="progress">
                <span style="color: #e6a23c">🚀 进行中</span>
              </el-option>
              <el-option label="已完成" value="completed">
                <span style="color: #67c23a">✅ 已完成</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="assignee" label="负责人" width="120" />
        <el-table-column prop="deadline" label="截止时间" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="120" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">👁️ 查看</el-button>
            <el-button size="small" type="primary" @click="assignTicket(row)" v-if="row.status === 'pending'">
              👥 分配
            </el-button>
            <el-button size="small" type="success" @click="completeTicket(row)" v-if="row.status === 'progress'">
              ✅ 完成
            </el-button>
            <el-button size="small" type="warning" @click="editTicket(row)">
              ✏️ 编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="tickets.length"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import { useRouter } from "vue-router"
import { ElMessage, ElMessageBox } from "element-plus"

const router = useRouter()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)

const searchForm = reactive({
  keyword: "",
  status: "",
  priority: ""
})

// 模拟数据
const tickets = ref([
  { id: 1, projectName: "电商管理系统", projectType: "web", priority: "high", status: "pending", assignee: "", deadline: "2024-02-15", createTime: "2024-01-15" },
  { id: 2, projectName: "移动端APP", projectType: "mobile", priority: "medium", status: "progress", assignee: "张三", deadline: "2024-03-01", createTime: "2024-01-10" },
  { id: 3, projectName: "数据分析平台", projectType: "data", priority: "urgent", status: "completed", assignee: "李四", deadline: "2024-01-30", createTime: "2024-01-05" }
])

const filteredTickets = computed(() => {
  let result = tickets.value
  if (searchForm.keyword) {
    result = result.filter(item => item.projectName.includes(searchForm.keyword))
  }
  if (searchForm.status) {
    result = result.filter(item => item.status === searchForm.status)
  }
  if (searchForm.priority) {
    result = result.filter(item => item.priority === searchForm.priority)
  }
  return result
})

const getProjectTypeText = (type) => {
  const map = { web: "Web应用", mobile: "移动应用", desktop: "桌面应用", api: "API接口", data: "数据分析" }
  return map[type] || type
}

const getPriorityText = (priority) => {
  const map = { low: " 低", medium: " 中", high: " 高", urgent: " 紧急" }
  return map[priority] || priority
}

const getPriorityType = (priority) => {
  const map = { low: "", medium: "warning", high: "danger", urgent: "danger" }
  return map[priority] || ""
}



const handleSearch = () => {
  console.log("搜索条件:", searchForm)
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ""
  })
}

const viewDetail = (row) => {
  router.push(`/ticket/detail/${row.id}`)
}

const assignTicket = (row) => {
  router.push(`/ticket/assign?id=${row.id}`)
}

// 处理状态变更
const handleStatusChange = (row) => {
  const statusMap = {
    pending: "待分配",
    progress: "进行中",
    completed: "已完成"
  }

  ElMessage.success(`工单 "${row.projectName}" 状态已更新为：${statusMap[row.status]}`)

  // 这里可以调用API更新后端数据
  console.log(`工单 ${row.id} 状态更新为: ${row.status}`)
}

// 完成工单
const completeTicket = (row) => {
  ElMessageBox.confirm(
    `确认将工单 "${row.projectName}" 标记为已完成吗？`,
    '确认操作',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'success',
    }
  ).then(() => {
    row.status = 'completed'
    ElMessage.success('工单已完成！')
  }).catch(() => {
    ElMessage.info('操作已取消')
  })
}

// 编辑工单
const editTicket = (row) => {
  ElMessage.info(`编辑工单 "${row.projectName}" 功能待开发`)
  // router.push(`/ticket/edit/${row.id}`)
}

onMounted(() => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
})
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 状态选择器样式 */
:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

/* 操作按钮样式 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 状态选择器下拉选项样式 */
:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
}
</style>
